<?php
// +----------------------------------------------------------------------
// | 小牛Admin
// +----------------------------------------------------------------------
// | Website: www.xnadmin.cn
// +----------------------------------------------------------------------
// | Author: dav <85168163@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller\curd\service;

class BuildControllerProgram
{
    //控制器的搜索条件
    public function buildSearch($data)
    {
        $search_condition = '';
        foreach ($data as $_data) {
            if ( $_data['search'] == 1) {
                if ( in_array($_data['form_type'], ['input', 'textarea', 'number']) ) {
                    $search_condition .= $this->createSearchCondition1($_data).PHP_EOL;
                } elseif ( in_array($_data['form_type'], ['radio', 'checkbox', 'select', 'switch'])) {
                    $search_condition .= $this->createSearchCondition2($_data).PHP_EOL;
                }
            }
        }
        $search_condition = trim($search_condition);
        $search_condition = str_replace('###', '$', $search_condition);
        return $search_condition;
    }

    //详细页的原始数据
    public function buildRawData($data)
    {
        $raw_data = '';
        foreach ($data as $_data) {
            if ( $_data['column'] == 1 && in_array($_data['form_type'], ['radio', 'checkbox', 'select', 'switch'])) {
                $raw_data .= $this->createRawData($_data).PHP_EOL;
            }
        }
        $raw_data = trim($raw_data);
        $raw_data = str_replace('###', '$', $raw_data);
        return $raw_data;
    }

    protected function createRawData($data)
    {
        $raw_data=<<<php
        ###data['{$data['field']}'] = ###_data->getData('{$data['field']}');
php;
        return $raw_data;
    }

    //控制器的搜索条件
    protected function createSearchCondition1($data)
    {
        $condition=<<<php
        if( ###param['{$data['field']}']!='' ) {
            ###model = ###model->whereLike('{$data['field']}',"%".###param['{$data['field']}']."%");
        }
php;
        return $condition;
    }

    protected function createSearchCondition2($data)
    {
        $condition=<<<php
        if( ###param['{$data['field']}']!='' ) {
            ###model = ###model->where('{$data['field']}',###param['{$data['field']}']);
        }
php;
        return $condition;
    }
}
